package dk.dtu.android.transport;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import dk.dtu.android.transport.SendSMS;

public class ReceiveSMS extends BroadcastReceiver {
	
	private String[] str2SearchFor = {"KLIP JA", "Besvar med JA"};
	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras(); 
		SmsMessage[] msgs = null;
		String phoneNo = ""; 
		String message = ""; 
		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			msgs = new SmsMessage[pdus.length];
			for (int i = 0; i < msgs.length; i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
				if(i == 0)
					phoneNo += msgs[i].getOriginatingAddress();
				message += msgs[i].getMessageBody().toString();
			}
		}
		Log.d("ReceiveSMS", "phoneNo: " + phoneNo);
		Log.d("ReceiveSMS", "message: " + message);
		
		if(phoneNo.equals("1990") || phoneNo.equals("1415")) 
			handleSMS(phoneNo, message, context);
		else
			Log.d("ReceiveSMS", "Did not handle received SMS");
	}
	
	private void handleSMS(String phoneNo, String message, Context context) {
		
			int index1990 = message.indexOf(str2SearchFor[0]);
			int index1415 = message.indexOf(str2SearchFor[1]);
			
			if (index1990 >= 0) { // String found
				if (phoneNo.equals("1990"))
					SendSMS.confirmSMS(phoneNo, "KLIP JA");
				Log.d("ReceiveSMS", "String found!");				
			}
			else if (index1415 >= 0) { // String found
				if (phoneNo.equals("1415"))
					SendSMS.confirmSMS(phoneNo, "JA");
				Log.d("ReceiveSMS", "String found!");				
			}
			else if((index1990 == -1) && (index1415 == -1)) { // String not found
				Toast.makeText(context, 
						"You do not appear to have any klips!",
						Toast.LENGTH_LONG).show();
				Log.d("ReceiveSMS", "No klips left!");

		}			
	}	
}